//
// Created by baigui on 21-7-19.
//


#ifndef SIMPLE_PLAYER_JNILAYER_H
#define SIMPLE_PLAYER_JNILAYER_H

#include <jni.h>
#include <stdlib.h>

struct fields {
    struct {
        jclass clazz;
    } IllegalStateException;

    struct {
        jclass clazz;
    } IllegalArgumentException;

    struct {
        jclass clazz;
    } RuntimeException;

    struct {
        jclass clazz;
    } OutOfMemoryError;

    struct {
        jfieldID mInstanceID;
        jclass clazz;
        jmethodID createTitleFromNativeID;
    } Spectrum;

}fields;

//struct fields fields;
extern struct fields fields;

static JavaVM *myVm;

extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = NULL;
    // Keep a reference on the Java VM.
    myVm = vm;

    if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK)
        return -1;

#define GET_CLASS(clazz, str, b_globlal) do { \
    (clazz) = env->FindClass((str)); \
    if (!(clazz)) { \
        return -1; \
    } \
    if (b_globlal) { \
        jclass local_class = (clazz); \
        (clazz) = (jclass) env->NewGlobalRef((clazz)); \
        env->DeleteLocalRef(local_class); \
        if (!(clazz)) { \
            return -1; \
        } \
    } \
} while (0)

#define GET_ID(get, id, clazz, str, args) do { \
    (id) = env->get((clazz), (str), (args)); \
    if (!(id)) { \
        return -1; \
    } \
} while (0)

    GET_CLASS(fields.IllegalStateException.clazz,
              "java/lang/IllegalStateException", true);
    GET_CLASS(fields.IllegalArgumentException.clazz,
              "java/lang/IllegalArgumentException", true);
    GET_CLASS(fields.RuntimeException.clazz,
              "java/lang/RuntimeException", true);
    GET_CLASS(fields.OutOfMemoryError.clazz,
              "java/lang/OutOfMemoryError", true);


    GET_CLASS(fields.Spectrum.clazz,
              "com/tview/visual/Spectrum", true);


    GET_ID(GetFieldID,
           fields.Spectrum.mInstanceID,
           fields.Spectrum.clazz,
           "mInstance", "J");

    return JNI_VERSION_1_6;

}

#endif //SIMPLE_PLAYER_JNILAYER_H
